#!/usr/bin/env python

import os
import wx
import app
import model
import dialog
import serial
import thread
import component

class Main(component.Presenter):
    '''Main class
    
    @author Julot <andy.julot@gmail.com>
    @since Saturday, January 14, 2012. 09:07 AM'''
    
    def __init__(self, view, interactor):
        super(Main, self).__init__(view, interactor)
        if not os.path.lexists('data'): os.mkdir('data')
        self.readColumnWidth()
    
    _stopped = True
    
    def onClose(self):
        if self._stopped:
            self.writeColumnWidth()
            super(Main, self).onClose()
            self.view.Destroy()
    
    def readColumnWidth(self):
        config = app.Config()
        for col in range(self.view.data.GetColumnCount() - 1):
            key = '%s/Col%s' % (self.view.Name, col)
            value = config.ReadInt(key, -1)
            if value != -1:
                self.view.data.SetColumnWidth(col, value)
    
    def writeColumnWidth(self):
        config = app.Config()
        for col in range(self.view.data.GetColumnCount() - 1):
            key = '%s/Col%s' % (self.view.Name, col)
            config.WriteInt(key, self.view.data.GetColumnWidth(col))
    
    def close(self):
        if self._stopped:
            self.view.Close()
    
    _about = None
    
    def showAbout(self):
        if not self._about: self._about = dialog.About(self.view)
        self._about.Center()
        self._about.Show()
    
    _hardware = None
    
    def loadHardware(self):
        if not self._hardware:
            config = app.Config()
            port = config.Read('GeoThermal/Port', 'COM1')
            baudrate = config.ReadInt('GeoThermal/Baudrate', 9600)
            try:
                self._hardware = serial.Serial(port, baudrate)
            except:
                self._hardware = None
        return self._hardware
        
    def start(self):
        hardware = self.loadHardware()
        if not hardware:
            self.view.messageDialog('Hardware is missing.', 'Error')
            return
        
        self._stopped = False
        self.view.start()
        thread.start_new_thread(self.readHardware, ())
    
    def readHardware(self):
        hardware = self.loadHardware()
        hardware.flushInput()
        geoThermal = model.GeoThermal()
        line = ''
        while not self._stopped:
            char = hardware.read()
            if char != '\r':
                line += char
                continue
            
            geoThermal.add(line.strip())
            geoThermal.save()
            wx.CallAfter(self.view.data.add, (geoThermal))
            geoThermal = model.GeoThermal()
            line = ''
    
    def stop(self):
        self.view.stop()
        self._stopped = True
    